package com.wonders.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wonders.dao.VoucherOrderMapper;
import com.wonders.dto.Result;
import com.wonders.entity.SeckillVoucher;
import com.wonders.entity.VoucherOrder;
import com.wonders.service.ISeckillVoucherService;
import com.wonders.service.IVoucherOrderService;
import com.wonders.utils.RedisIdUtils;
import com.wonders.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 功能描述:优惠券-订单信息服务实现类
 * @Author: yyalin
 * @CreateDate: 2023/8/11 15:07
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private RedisIdUtils redisIdWorker;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private RedissonClient redissonClient;
    /**************第一种方法：比较耗时*********************/
    @Override
    public Result seckillVoucher(Long voucherId) {
        // 1.查询秒杀优惠券
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        log.info("查询的优惠券为voucher："+voucher);
        // 2.判断秒杀是否开始
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            // 尚未开始
            return Result.fail("秒杀尚未开始！");
        }
        // 3.判断秒杀是否已经结束
        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
            // 秒杀结束
            return Result.fail("秒杀已经结束！");
        }
        // 4.判断库存是否充足
        if (voucher.getStock() < 1) {
            // 库存不足
            return Result.fail("库存不足！");
        }
        //获取用户ID
//        Long userId = UserHolder.getUser().getId();
        Long userId =999L;  //暂时用户写死
        // 创建锁对象
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        // 尝试获取锁
        boolean isLock = lock.tryLock();
        // 判断是否获取锁成功
        if(!isLock){
            // 获取锁失败，返回错误或重试
            return Result.fail("不允许重复下单");
        }
        //获取锁成功、处理相关业务
        try {
            // 获取代理对象（事务）
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId);
            return this.createVoucherOrder(voucherId);
        } finally {
            // 释放锁
            lock.unlock();
        }
    }


    @Transactional
    public Result createVoucherOrder(Long voucherId) {
        // 5.一人一单
        //Long userId = UserHolder.getUser().getId();
        Long userId =999L;  //暂时用户写死
        synchronized (userId.toString().intern()) {
            // 5.1.查询订单
            int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
            // 5.2.判断是否存在
            if (count > 0) {
                // 用户已经购买过了
                return Result.fail("用户已经购买过一次！");
            }

            // 6.扣减库存
            boolean success = seckillVoucherService.update()
                    .setSql("stock = stock - 1") // set stock = stock - 1
                    .eq("voucher_id", voucherId).gt("stock", 0) // where id = ? and stock > 0
                    .update();
            if (!success) {
                // 扣减失败
                return Result.fail("库存不足！");
            }

            // 7.创建订单
            VoucherOrder voucherOrder = new VoucherOrder();
            // 7.1.订单id
            long orderId = redisIdWorker.nextId("order");
            voucherOrder.setId(orderId);
            // 7.2.用户id
            voucherOrder.setUserId(userId);
            // 7.3.代金券id
            voucherOrder.setVoucherId(voucherId);
            save(voucherOrder);

            // 7.返回订单id
            return Result.ok(orderId);
        }
    }
    /**************第二种方法：异步的方式*********************/





}
